package com.album.activity;

 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.album.R;
import com.album.activity.base.BaseActivity;
import com.album.utils.MyLog;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ViewFlipper;

public class CofImageFolderList extends Activity implements Runnable {
	private ArrayList<String> filelist = new ArrayList<String>();	//文件夹
	private FolderAdapter adapter;
	private ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
	private GridView  folderList;
	private ProgressDialog dialog;
	private String path;
	private List<String> filePaths = new ArrayList<String>();
	private List<String> imageCounts = new ArrayList<String>();
	private BitmapFactory.Options options;
	private List<String> paths = new ArrayList<String>();
	private List<Bitmap> folderBitmaps;
	private Button btnBack;
	private int index;
	private Bitmap defaultBitmap;
	public static ArrayList<HashMap<String, String>> pathList = new ArrayList<HashMap<String, String>>(); 
	private ViewFlipper viewflipper;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.folder_list);  
		defaultBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
		folderList = (GridView) findViewById(R.id.folderList);
		viewflipper = (ViewFlipper)findViewById(R.id.viewflipper);
		folderList.setCacheColorHint(0);
		btnBack = (Button) findViewById(R.id.btnBack);
		options = new BitmapFactory.Options();
		// 跳转到图片选择界面
		folderList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				MyLog.debug(getClass(), "filePaths.get(position):"+filePaths.get(position));
				MyLog.debug(getClass(), "imageCounts.get(position):"+imageCounts.get(position));
				backEvent(CoOfImageListActivity.class, filePaths.get(position), imageCounts.get(position));
			}
		});
		// 返回模式选择界面
		btnBack.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				backEvent(HomeActivity.class, null, null);
				return true;
			}
		});
		if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
			if (dialog == null) {
				dialog = ProgressDialog.show(this, null, null);
			} else {
				dialog.show();
			}
			Thread thread = new Thread(this);
			thread.start();
		} else {
			Toast.makeText(CofImageFolderList.this, "sd_error", Toast.LENGTH_SHORT).show();
		}
		viewflipper.setDisplayedChild(1);
	}

	@Override
	protected void onPause() { 
		super.onPause();
	}

	@Override
	protected void onResume() { 
		super.onResume();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
//			backEvent(HomeActivity.class, null, null);
		}
		return super.onKeyDown(keyCode, event);
	}

	private void findImage() {
		Uri originalUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		ContentResolver cr = this.getContentResolver();
		Cursor cursor = cr.query(originalUri, null, null, null, null);
		cursor.moveToFirst();
		String tempString, string;
		// int id;
		// 获取有图片的文件夹名称
		try {
			for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
				// id = cursor.getInt(cursor.getColumnIndex("_ID"));
				path = cursor.getString(cursor.getColumnIndex("_data"));
				tempString = path.substring(0, path.lastIndexOf("/"));
				// string是图片文件夹的完整路径
				string = tempString.substring(tempString.lastIndexOf("/") + 1);
				// 添加文件夹名称，并将这个文件夹下面的图片数设为1.
				if (!filelist.contains(string)) {
					filelist.add(string);
					// 添加图片文件夹的完整路径
					filePaths.add(tempString);
					imageCounts.add(filelist.indexOf(string), String.valueOf(1));
					MyLog.debug(getClass(), 
							"string:"+string+"\t"+
							"tempString:"+tempString+"\t"+
							"path:"+path);
					paths.add(path);
				} else {
					// 已有这个文件夹名称，将这个文件夹下的图片数加1.
					imageCounts.set(filelist.indexOf(string), Integer.parseInt(imageCounts
							.get(filelist.indexOf(string)))
							+ 1 + "");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (cursor != null) {
			cursor.close();
		}
	}

	private void setAdapter() {
		HashMap<String, Object> map;

		for (int i = 0; i < filelist.size(); i++) {
			map = new HashMap<String, Object>();
			map.put("path", filelist.get(i));
			map.put("image", "" + i);
			map.put("count", "(" + imageCounts.get(i) + ")");
			data.add(map);
			map = null;
		}
		adapter = new FolderAdapter(this, data, R.layout.folder_list_item, new String[] { "path", "image", "count" },
				new int[] { R.id.pathText, R.id.folderImage, R.id.countText });
		folderList.setAdapter(adapter);
		index = 0;
		Thread thread = new Thread(CofImageFolderList.this);
		thread.start();
	}

	@Override
	public void run() {
		if (folderList.getAdapter() == null) {
			findImage();
			handler.sendEmptyMessage(1);
		} 
		else {
			MyLog.info(getClass(), "folderList ,,,,");
			String path;
			// Bitmap bitmap = null;
			folderBitmaps = new ArrayList<Bitmap>();
			MyLog.info(getClass(), "pathsSize:"+paths.size());
			
			for (int i = 0, l = paths.size(); i < l; i++) {
				path = paths.get(i);
				if (path.contains("100ANDRO")) {
					options.inSampleSize = 2;
				} else {
					options.inSampleSize = 2;
				}
				// bitmap = BitmapFactory.decodeFile(path, options);
				if (folderBitmaps != null) {
					try {
						if (path != null) {
							folderBitmaps.add(BitmapFactory.decodeFile(path, options));
						} else {
							folderBitmaps.add(defaultBitmap);
						}
						handler.sendEmptyMessage(2);
					} catch (OutOfMemoryError e) {	
						e.printStackTrace();break;
					} catch (IndexOutOfBoundsException e) {	
						e.printStackTrace();break;
					}
				} else {
					break;
				}
			}
		}
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (dialog != null) {
				dialog.dismiss();
				dialog = null;
			}
			if (msg.what == 1) {
				setAdapter();
			} else if (msg.what == 2) {
				if (adapter != null) {
					MyLog.info(getClass(), "notifyDataSetChanged...");
					adapter.notifyDataSetChanged();
				}
			}
		}
	};

	private void backEvent(Class<?> cls, String extraString, String imageCount) {
		Intent intent = new Intent(CofImageFolderList.this, cls);
		if (extraString != null) {
			intent.putExtra("filePath", extraString);
			intent.putExtra("fileCount", Integer.parseInt(imageCount));
		}
		CofImageFolderList.this.startActivity(intent);
		intent = null;
		adapter = null;
		if (folderList != null) {
			folderList.setVisibility(View.GONE);
			folderList = null;
		}
		finish();
		MyLog.debug(getClass(), "folderBitmaps:"+folderBitmaps.size());
		if (folderBitmaps != null && folderBitmaps.size() > 0) {
			for (int i = 0, l = folderBitmaps.size(); i < l; i++) {
				if (folderBitmaps.get(i) != null && !folderBitmaps.get(i).isRecycled()) {
					folderBitmaps.get(i).recycle();
				}
			}
			folderBitmaps.clear();
			folderBitmaps = null;
		}
	}

	class FolderAdapter extends SimpleAdapter {
		public FolderAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
			super(context, data, resource, from, to);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			index = position;
			return super.getView(position, convertView, parent);
		}

		@Override
		public void setViewImage(ImageView v, String value) {
			try {
				v.setImageBitmap(null);
				if (folderBitmaps != null && index < folderBitmaps.size() && folderBitmaps.get(index) != null
						&& !folderBitmaps.get(index).isRecycled()) {
					v.setImageBitmap(folderBitmaps.get(index));
				}
			} catch (IndexOutOfBoundsException e) {
				e.printStackTrace();
			}
		}

	} 

}
